package com.business.business.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.business.business.common.base.BaseService;
import com.business.business.model.Business;
import com.business.business.model.Certificate;
import com.business.business.model.DeviceBusiness;
import com.business.business.support.model.RespEntity;
import com.business.business.support.mybatisplus.QueryWrapper;
import com.business.business.support.utils.https.StringUtil;
import com.business.business.support.utils.requestutil.HttpRequestUtil;
import com.business.business.web.mapper.BusinessMapper;
import com.business.business.web.mapper.CertificateMapper;
import com.business.business.web.mapper.DeviceBusinessMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Service
public class EnterpriseService extends BaseService {

    @Resource
    private BusinessMapper businessMapper;

    @Resource
    private CertificateMapper certificateMapper;

    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 区域概况查询
     */
    public RespEntity getRegionalInfo(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String areaId = jsonObject.getStr("areaId");
        if (StringUtil.strIsNullOrEmpty(areaId)) {
            return RespEntity.fail("请填写areaId");
        }

        // 查询该区域下企业
        LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Business::getArea, areaId)
                .select(Business::getId);
        List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
        List<String> ids = new ArrayList<>();
        for (Business business : businesses) {
            ids.add(business.getId());
        }

        // 查询该区域下消防等级分类
        // 消防安全重点单位
        LambdaQueryWrapper<Business> lambdaQueryWrapperEmphasis = new LambdaQueryWrapper<>();
        lambdaQueryWrapperEmphasis.like(Business::getArea, areaId).eq(Business::getFireRating, "001e7548-8735-4b31-b30b-c9361a62c901");
        Integer emphasis = businessMapper.selectCount(lambdaQueryWrapperEmphasis);
        // 消防安全一般单位
        LambdaQueryWrapper<Business> lambdaQueryWrapperCommon = new LambdaQueryWrapper<>();
        lambdaQueryWrapperCommon.like(Business::getArea, areaId).eq(Business::getFireRating, "001e7548-8735-4b31-b30b-c9361a62c902");
        Integer common = businessMapper.selectCount(lambdaQueryWrapperCommon);
        // 九小
        LambdaQueryWrapper<Business> lambdaQueryWrapperPlace = new LambdaQueryWrapper<>();
        lambdaQueryWrapperPlace.like(Business::getArea, areaId).eq(Business::getFireRating, "001e7548-8735-4b31-b30b-c9361a62c903");
        Integer placeNumber = businessMapper.selectCount(lambdaQueryWrapperPlace);
        // 其他
        LambdaQueryWrapper<Business> lambdaQueryWrapperOther = new LambdaQueryWrapper<>();
        lambdaQueryWrapperOther.like(Business::getArea, areaId).eq(Business::getFireRating, "001e7548-8735-4b31-b30b-c9361a62c904");
        Integer otherNumber = businessMapper.selectCount(lambdaQueryWrapperOther);
        // 计算比率
        Double sum = (double) (emphasis + common + placeNumber + otherNumber);
        String emphasisRate = String.format("%.2f", emphasis * 100.00 / sum);
        String commonRate = String.format("%.2f", common * 100.00 / sum);
        String placeRate = String.format("%.2f", placeNumber * 100.00 / sum);
        String otherRate = String.format("%.2f", otherNumber * 100.00 / sum);
        if ("NaN".equals(emphasisRate)) {
            emphasisRate = "0";
        }
        if ("NaN".equals(commonRate)) {
            commonRate = "0";
        }
        if ("NaN".equals(placeRate)) {
            placeRate = "0";
        }
        if ("NaN".equals(otherRate)) {
            otherRate = "0";
        }
        // 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("businessNumber", ids.size());
        map.put("emphasisRate", emphasisRate);
        map.put("commonRate", commonRate);
        map.put("placeRate", placeRate);
        map.put("otherRate", otherRate);

        return RespEntity.success(map);
    }

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 辖区行业分布情况
     */
    public RespEntity getIndustryInfo(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String areaId = jsonObject.getStr("areaId");
        if (StringUtil.strIsNullOrEmpty(areaId)) {
            return RespEntity.fail("请填写areaId");
        }

        // 查询该区域下企业
        LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Business::getArea, areaId)
                .select(Business::getId);
        List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (businesses.isEmpty()) {
            map.put("miningIndustry", 0);
            map.put("manufacturingIndustry", 0);
            map.put("electricIndustry", 0);
            map.put("constructionIndustry", 0);
            map.put("traIndustry", 0);
            map.put("OtherIndustry", 0);
            return RespEntity.success(map);
        }
        List<String> ids = new ArrayList<>();
        for (Business business : businesses) {
            ids.add(business.getId());
        }

        // 01
        // 查询企业的所属行业数量
        // 采矿业
        Object miningIndustry = businessMapper.selectIndustryCount(ids, "01");
        // 制造业
        Object manufacturingIndustry = businessMapper.selectIndustryCount(ids, "02");
        // 电力、燃气及水的生产和供应业
        Object electricIndustry = businessMapper.selectIndustryCount(ids, "03");
        // 建筑业
        Object constructionIndustry = businessMapper.selectIndustryCount(ids, "04");
        // 交通运输、仓储和邮政业
        Object traIndustry = businessMapper.selectIndustryCount(ids, "05");
        // 其他
        Object OtherIndustry = businessMapper.selectIndustryCountOther(ids);


        map.put("miningIndustry", miningIndustry);
        map.put("manufacturingIndustry", manufacturingIndustry);
        map.put("electricIndustry", electricIndustry);
        map.put("constructionIndustry", constructionIndustry);
        map.put("traIndustry", traIndustry);
        map.put("OtherIndustry", OtherIndustry);
        return RespEntity.success(map);
    }

    /**
     * Author: xulumin
     * Date: 2024/3/19
     * Description: 辖区预警提醒
     */
    public RespEntity getAreaWarning(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String areaId = jsonObject.getStr("areaId");
        if (StringUtil.strIsNullOrEmpty(areaId)) {
            return RespEntity.fail("请填写areaId");
        }
        // 查询企业
        LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Business::getArea, areaId).select(Business::getId);
        List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
        List<String> ids = new ArrayList<>();
        for (Business business : businesses) {
            ids.add(business.getId());
        }

        // 1人员证书 2 设备设施 3第三方检验 4 行业资质5标准化达标
        LocalDate current = LocalDate.now();
        // 获取比现在早5天的日期
        LocalDate fiveDaysAgo = current.minusDays(5);

        // 人员证书 已过期
        QueryWrapper<Certificate> queryWrapper = new QueryWrapper();
        queryWrapper.in("business_id", ids);

        queryWrapper.lt("due_date", current).eq("type", 1);
        int peopleCertificateDue = certificateMapper.selectCount(queryWrapper);
        // 预过期
        queryWrapper.gt("due_date", fiveDaysAgo);
        int peopleCertificateWill = certificateMapper.selectCount(queryWrapper);

        // 设备设施证书 已过期
        QueryWrapper<Certificate> queryWrapperDevice = new QueryWrapper();
        queryWrapperDevice.in("business_id", ids).lt("due_date", current).eq("type", 2);
        int deviceCertificateDue = certificateMapper.selectCount(queryWrapper);
        // 预过期
        queryWrapperDevice.gt("due_date", fiveDaysAgo);
        int deviceCertificateWill = certificateMapper.selectCount(queryWrapper);


        // 第三方检验 已过期
        QueryWrapper<Certificate> thirdWrapperDevice = new QueryWrapper();
        thirdWrapperDevice.in("business_id", ids).lt("due_date", current).eq("type", 3);
        int thirdCertificateDue = certificateMapper.selectCount(queryWrapper);
        // 预过期
        thirdWrapperDevice.gt("due_date", fiveDaysAgo);
        int thirdCertificateWill = certificateMapper.selectCount(queryWrapper);

        // 行业资质证书 已过期
        QueryWrapper<Certificate> industryWrapperDevice = new QueryWrapper();
        industryWrapperDevice.in("business_id", ids).lt("due_date", current).eq("type", 4);
        int industryCertificateDue = certificateMapper.selectCount(queryWrapper);
        // 预过期
        industryWrapperDevice.gt("due_date", fiveDaysAgo);
        int industryCertificateWill = certificateMapper.selectCount(queryWrapper);

        // 标准化达标证书 已过期
        QueryWrapper<Certificate> standardWrapperDevice = new QueryWrapper();
        standardWrapperDevice.in("business_id", ids).lt("due_date", current).eq("type", 5);
        int standardCertificateDue = certificateMapper.selectCount(queryWrapper);
        // 预过期
        standardWrapperDevice.gt("due_date", fiveDaysAgo);
        int standardCertificateWill = certificateMapper.selectCount(queryWrapper);

        // 组装数据
        List<JSONObject> list = new ArrayList<>();
        JSONObject jsonObjectPeopleCertificate = new JSONObject();
        jsonObjectPeopleCertificate.put("name", "人员证书");
        jsonObjectPeopleCertificate.put("expired", peopleCertificateDue);
        jsonObjectPeopleCertificate.put("unexpired", peopleCertificateWill);
        JSONObject jsonObjectDeviceCertificate = new JSONObject();
        jsonObjectDeviceCertificate.put("name", "设备设施");
        jsonObjectDeviceCertificate.put("expired", deviceCertificateDue);
        jsonObjectDeviceCertificate.put("unexpired", deviceCertificateWill);
        JSONObject jsonObjectStandardCertificate = new JSONObject();
        jsonObjectStandardCertificate.put("name", "标准化达标证书");
        jsonObjectStandardCertificate.put("expired", standardCertificateDue);
        jsonObjectStandardCertificate.put("unexpired", standardCertificateWill);
        JSONObject jsonObjectIndustryCertificate = new JSONObject();
        jsonObjectIndustryCertificate.put("name", "行业资质证书");
        jsonObjectIndustryCertificate.put("expired", industryCertificateDue);
        jsonObjectIndustryCertificate.put("unexpired", industryCertificateWill);
        list.add(jsonObjectPeopleCertificate);
        list.add(jsonObjectDeviceCertificate);
        list.add(jsonObjectStandardCertificate);
        list.add(jsonObjectIndustryCertificate);

        return RespEntity.success(list);
    }

    /**
     * @Author: xulumin
     * @ClassName: DeviceSwitchController
     * @Date: Created in 9:23 2024.03.26
     * @Description: 一企一档大屏查询设备报警
     */
    public RespEntity getAreaDeviceInfo(JSONObject jsonObject) {
        //处理支持form-data和json两种方式
        jsonObject = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonObject, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String homeId = token.getString("home_id");
        String userId = token.getString("user_id");
        String userType = token.getString("user_type");

        String areaId = jsonObject.getStr("areaId");
        if (StringUtil.strIsNullOrEmpty(areaId)) {
            return RespEntity.fail("请填写areaId");
        }
        // 查询企业
        LambdaQueryWrapper<Business> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(Business::getArea, areaId).select(Business::getId);
        List<Business> businesses = businessMapper.selectList(lambdaQueryWrapper);
        List<String> ids = new ArrayList<>();
        for (Business business : businesses) {
            ids.add(business.getId());
        }

        // 查询企业下每种设备的报警数量
        LambdaQueryWrapper<DeviceBusiness> lambdaQueryDevice = new LambdaQueryWrapper<>();
        lambdaQueryDevice.in(DeviceBusiness::getBusinessId, ids)
                // 状态为报警的
                .eq(DeviceBusiness::getCurrentstate, "2")
                // 电器火灾设备类型
                .eq(DeviceBusiness::getDeviceClassify, "1");
        // 电器火灾设备报警
        Integer electricalNumber = deviceBusinessMapper.selectCount(lambdaQueryDevice);
        // 消防用水
        Integer waterNumber = deviceBusinessMapper.selectCount(new LambdaQueryWrapper<DeviceBusiness>().in(DeviceBusiness::getBusinessId, ids).eq(DeviceBusiness::getCurrentstate, "2").eq(DeviceBusiness::getDeviceClassify, "2"));
        // 独立烟感
        Integer smokeNumber = deviceBusinessMapper.selectCount(new LambdaQueryWrapper<DeviceBusiness>().in(DeviceBusiness::getBusinessId, ids).eq(DeviceBusiness::getCurrentstate, "2").eq(DeviceBusiness::getDeviceClassify, "3"));
        // 可燃气检测
        Integer gasNumber = deviceBusinessMapper.selectCount(new LambdaQueryWrapper<DeviceBusiness>().in(DeviceBusiness::getBusinessId, ids).eq(DeviceBusiness::getCurrentstate, "2").eq(DeviceBusiness::getDeviceClassify, "4"));
        // 智慧视频
        Integer viewNumber = deviceBusinessMapper.selectCount(new LambdaQueryWrapper<DeviceBusiness>().in(DeviceBusiness::getBusinessId, ids).eq(DeviceBusiness::getCurrentstate, "2").eq(DeviceBusiness::getDeviceClassify, "6"));
        // 其他设备报警数量
        List<String> list = new ArrayList<String>();
        list.add("5");
        list.add("7");
        list.add("8");
        list.add("9");
        list.add("10");
        Integer otherNumber = deviceBusinessMapper.selectCount(new LambdaQueryWrapper<DeviceBusiness>().in(DeviceBusiness::getBusinessId, ids).eq(DeviceBusiness::getCurrentstate, "2").notIn(DeviceBusiness::getDeviceClassify, list));
        // 组装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("electricalNumber", electricalNumber);
        map.put("waterNumber", waterNumber);
        map.put("smokeNumber", smokeNumber);
        map.put("gasNumber", gasNumber);
        map.put("viewNumber", viewNumber);
        map.put("otherNumber", otherNumber);

        return RespEntity.success(map);
    }
}
